package com.guigu.financial.controller;

import com.github.pagehelper.PageInfo;
import com.guigu.financial.pojo.Borrower;
import com.guigu.financial.pojo.vo.BorrowerApprovalVO;
import com.guigu.financial.service.BorrowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@CrossOrigin
@RequestMapping("/borrower")
public class BorrowerController {
    @Autowired
    BorrowerService borrowerService;

    @GetMapping("")
    public PageInfo findByBorrower(@RequestParam(required = false)String keyword, @RequestParam(required = false) int pageNum, int limit){
        Borrower borrower = new Borrower();
        //判断是否为手机号
        if (keyword.length()==11){
            borrower.setMobile(keyword);
        }
        //判断是否为中文
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(keyword);
        if (m.find()) {
            borrower.setName(keyword);
        }
        //判断是否为手机号
        if (keyword.length()==18){
            borrower.setIdCard(keyword);
        }
        PageInfo byBorrower = borrowerService.findByBorrower(pageNum, limit, borrower);
        return byBorrower;
    }

    @PutMapping("")
    public void update(@RequestBody Borrower borrower){
        borrowerService.updateByPrimaryKeySelective(borrower);
    }

    @PostMapping("approval")
    public void borrowerApproval(@RequestBody BorrowerApprovalVO borrowerApprovalVO){
        borrowerService.approval(borrowerApprovalVO);
    }

    // 保存borrower到ServletContext中
    @PostMapping("")
    public void saveBorrowerInServletContext(@RequestBody Borrower borrower, HttpServletRequest request){
        request.getServletContext().setAttribute("borrower",borrower);
    }

    @GetMapping("getBorrower")
    public Borrower findDetail(Integer id, HttpServletRequest request){
        Borrower borrower = (Borrower) request.getServletContext().getAttribute("borrower");
        return borrower;
    }

}
